<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>备份恢复 - 密钥管理服务</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <!-- 共享响应式样式 -->
    <link href="shared_responsive.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8fafc;
            background-image: radial-gradient(rgba(59, 130, 246, 0.05) 1px, transparent 1px);
            background-size: 20px 20px;
            background-position: 0 0, 10px 10px;
            color: #334155;
        }
        .fade-in {
            animation: fadeIn 0.5s ease-in-out;
        }
        .badge-success {
            background-color: rgba(16, 185, 129, 0.15);
            color: #10b981;
        }
        .badge-warning {
            background-color: rgba(234, 179, 8, 0.15);
            color: #d97706;
        }
        .progress-bar {
            transition: width 0.5s ease;
        }
        .card {
            background-color: rgba(255, 255, 255, 0.9);
            border: 1px solid rgba(59, 130, 246, 0.4);
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.02);
            transition: all 0.3s ease;
        }
        .card:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.04);
        }
        .btn {
            transition: all 0.3s ease;
        }
        .btn-primary {
            background-color: rgba(59, 130, 246, 0.15);
            color: #3b82f6;
            border: 1px solid rgba(59, 130, 246, 0.3);
        }
        .btn-primary:hover {
            background-color: rgba(59, 130, 246, 0.25);
        }
        .btn-success {
            background-color: rgba(16, 185, 129, 0.15);
            color: #10b981;
            border: 1px solid rgba(16, 185, 129, 0.3);
        }
        .btn-success:hover {
            background-color: rgba(16, 185, 129, 0.25);
        }
        .btn-danger {
            background-color: rgba(239, 68, 68, 0.15);
            color: #ef4444;
            border: 1px solid rgba(239, 68, 68, 0.3);
        }
        .btn-danger:hover {
            background-color: rgba(239, 68, 68, 0.25);
        }
        .input-field {
            background-color: rgba(255, 255, 255, 0.8);
            border: 1px solid rgba(59, 130, 246, 0.3);
            border-radius: 8px;
            transition: all 0.3s ease;
        }
        .input-field:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        .table-row {
            transition: all 0.2s ease;
        }
        .table-row:hover {
            background-color: rgba(59, 130, 246, 0.05);
        }
        .back-btn {
            transition: all 0.3s ease;
        }
        .back-btn:hover {
            background-color: rgba(59, 130, 246, 0.1);
        }
        .file-input {
            position: relative;
            overflow: hidden;
            display: inline-block;
        }
        .file-input input[type="file"] {
            position: absolute;
            top: 0;
            left: 0;
            opacity: 0;
            cursor: pointer;
        }
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        .status-badge.manual {
            background-color: rgba(59, 130, 246, 0.15);
            color: #3b82f6;
        }
        .status-badge.auto {
            background-color: rgba(16, 185, 129, 0.15);
            color: #10b981;
        }
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(4px);
        }
        .modal.show {
            display: block;
            animation: fadeIn 0.3s ease;
        }
        .modal-content {
            background-color: rgba(255, 255, 255, 0.95);
            margin: 5% auto;
            padding: 1.5rem;
            border: 1px solid rgba(59, 130, 246, 0.4);
            border-radius: 12px;
            width: 90%;
            max-width: 500px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
            animation: slideUp 0.3s ease;
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
        }
        .modal-title {
            font-size: 1.25rem;
            font-weight: 600;
            color: #334155;
        }
        .close {
            color: #94a3b8;
            font-size: 1.5rem;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .close:hover {
            color: #334155;
        }
        .toast {
            position: fixed;
            top: 1rem;
            right: 1rem;
            padding: 1rem 1.5rem;
            border-radius: 8px;
            color: white;
            font-weight: 500;
            z-index: 10000;
            opacity: 0;
            transform: translateY(-20px);
            transition: all 0.3s ease;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
        .toast.show {
            opacity: 1;
            transform: translateY(0);
        }
        .toast.success {
            background-color: rgba(16, 185, 129, 0.9);
        }
        .toast.error {
            background-color: rgba(239, 68, 68, 0.9);
        }
        .toast.info {
            background-color: rgba(59, 130, 246, 0.9);
        }
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        @keyframes slideUp {
            from { transform: translateY(20px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid rgba(59, 130, 246, 0.3);
            border-radius: 50%;
            border-top-color: #3b82f6;
            animation: spin 1s ease-in-out infinite;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        .empty-state {
            text-align: center;
            padding: 3rem;
            color: #94a3b8;
        }
        .empty-state i {
            font-size: 3rem;
            margin-bottom: 1rem;
            opacity: 0.5;
        }
    </style>
</head>
<body class="p-6">
    <!-- 背景网格层 -->
    <article class="fixed inset-0 z-0">
        <!-- 背景网格图案已在body样式中定义 -->
    </article>
    
    <!-- 主要内容层 -->
    <section class="relative z-10">
        <!-- 页面标题区 -->
        <header class="mb-6 flex items-center justify-between">
            <h1 class="text-3xl font-bold text-gray-800">密钥备份恢复</h1>
            <div class="flex gap-3">
                <button class="btn btn-success px-4 py-2 flex items-center gap-2" onclick="createBackup()">
                    <i class="fas fa-database"></i>
                    <span>创建备份</span>
                </button>
                <a href="index.html" class="back-btn px-4 py-2 rounded-lg flex items-center gap-2 text-gray-600">
                    <i class="fas fa-arrow-left"></i>
                    <span>返回首页</span>
                </a>
            </div>
        </header>
        
        <!-- Toast 通知容器 -->
        <div id="toastContainer"></div>

        <!-- 备份恢复操作 -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
            <!-- 手动备份 -->
            <div class="card p-6">
                <h2 class="text-xl font-semibold mb-4">手动备份</h2>
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">备份范围</label>
                        <div class="space-y-2">
                            <div class="flex items-center gap-2">
                                <input type="radio" name="backupScope" id="allKeys" value="all" class="text-blue-600 focus:ring-blue-500" checked>
                                <label for="allKeys" class="text-sm text-gray-700">所有密钥</label>
                            </div>
                            <div class="flex items-center gap-2">
                                <input type="radio" name="backupScope" id="selectedKeys" value="selected" class="text-blue-600 focus:ring-blue-500">
                                <label for="selectedKeys" class="text-sm text-gray-700">选择的密钥</label>
                            </div>
                        </div>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">备份密码</label>
                        <input type="password" class="input-field w-full px-4 py-2" id="backupPassword" placeholder="设置备份密码（至少6位）">
                        <div id="passwordStrength" class="text-xs mt-1 text-gray-500"></div>
                    </div>
                    <button class="btn btn-primary px-4 py-2 rounded-lg w-full flex items-center justify-center gap-2" onclick="manualBackup()">
                        <i class="fas fa-download"></i> <span id="backupBtnText">开始备份</span>
                        <span id="backupLoading" class="loading hidden"></span>
                    </button>
                </div>
            </div>

            <!-- 恢复备份 -->
            <div class="card p-6">
                <h2 class="text-xl font-semibold mb-4">恢复备份</h2>
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">选择备份文件</label>
                        <div class="file-input">
                            <button class="btn btn-primary px-4 py-2 rounded-lg w-full">
                                <i class="fas fa-file-import"></i> 选择文件
                            </button>
                            <input type="file" id="backupFile" accept=".json">
                        </div>
                        <div id="fileName" class="text-sm text-gray-500 mt-2"></div>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">备份密码</label>
                        <input type="password" class="input-field w-full px-4 py-2" id="restorePassword" placeholder="输入备份密码">
                    </div>
                    <button class="btn btn-primary px-4 py-2 rounded-lg w-full flex items-center justify-center gap-2" onclick="restoreBackup()">
                        <i class="fas fa-upload"></i> <span id="restoreBtnText">开始恢复</span>
                        <span id="restoreLoading" class="loading hidden"></span>
                    </button>
                </div>
            </div>
        </div>

        <!-- 备份配置卡片 -->
        <div class="card p-6 fade-in">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between mb-6">
                <h2 class="text-xl font-semibold">备份配置</h2>
                <button class="btn btn-primary px-4 py-2" onclick="openBackupConfigModal()">
                    <i class="fas fa-cog"></i>
                    <span>配置</span>
                </button>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div class="bg-blue-50 p-4 rounded-lg">
                    <p class="text-sm text-gray-600">备份模式</p>
                    <p class="text-lg font-medium mt-1" id="backupMode">定时备份</p>
                </div>
                <div class="bg-green-50 p-4 rounded-lg">
                    <p class="text-sm text-gray-600">备份周期</p>
                    <p class="text-lg font-medium mt-1" id="backupCycle">每日 23:00</p>
                </div>
                <div class="bg-purple-50 p-4 rounded-lg">
                    <p class="text-sm text-gray-600">备份保留</p>
                    <p class="text-lg font-medium mt-1" id="backupRetention">30 天</p>
                </div>
            </div>
        </div>
        
        <!-- 备份历史 -->
        <div class="card p-6 mt-6">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between mb-6 gap-4">
                <h2 class="text-xl font-semibold">备份历史</h2>
                <div class="relative">
                    <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                    <input type="text" id="backupSearch" class="input-field pl-10 pr-4 py-2 w-full md:w-64" placeholder="搜索备份...">
                </div>
            </div>
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead>
                        <tr class="border-b border-gray-200">
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">备份ID</th>
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">备份时间</th>
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">密钥数量</th>
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">备份大小</th>
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">类型</th>
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">操作</th>
                        </tr>
                    </thead>
                    <tbody id="backupHistoryTableBody">
                <!-- 备份历史数据将通过JavaScript动态生成 -->
            </tbody>
                </table>
            </div>
        </div>
        
        <!-- 备用密钥管理 -->
        <div class="card p-6 mt-6">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between mb-6 gap-4">
                <h2 class="text-xl font-semibold">备用密钥管理</h2>
                <button class="btn btn-primary px-4 py-2 flex items-center gap-2" onclick="generateSpareKeys()">
                    <i class="fas fa-key"></i>
                    <span>生成备用密钥</span>
                </button>
            </div>
            
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead>
                        <tr class="border-b border-gray-200">
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">密钥ID</th>
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">对应的主密钥</th>
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">生成时间</th>
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">状态</th>
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">操作</th>
                        </tr>
                    </thead>
                    <tbody id="spareKeysTableBody">
                        <!-- 备用密钥数据将通过JavaScript动态生成 -->
                    </tbody>
                </table>
            </div>
        </div>
    </section>

    <!-- 引入通用功能组件 -->
    <script src="common.js"></script>
    <!-- 备份配置模态框 -->
    <div id="backupConfigModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">备份配置</h3>
                <span class="close" onclick="closeBackupConfigModal()">&times;</span>
            </div>
            
            <form id="backupConfigForm" onsubmit="submitBackupConfig(event)">
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">备份模式</label>
                        <select id="configBackupMode" class="input-field w-full px-4 py-2" required>
                            <option value="manual">手动备份</option>
                            <option value="scheduled">定时备份</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">备份周期</label>
                        <select id="configBackupCycle" class="input-field w-full px-4 py-2">
                            <option value="daily">每日 23:00</option>
                            <option value="weekly">每周日 23:00</option>
                            <option value="monthly">每月1日 23:00</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">备份保留天数</label>
                        <input type="number" id="configBackupRetention" class="input-field w-full px-4 py-2" min="1" max="365" value="30" required>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">备份加密方式</label>
                        <select id="configBackupEncryption" class="input-field w-full px-4 py-2" required>
                            <option value="SM4">SM4</option>
                            <option value="AES">AES</option>
                        </select>
                    </div>
                </div>
                
                <div class="mt-6 flex justify-end gap-3">
                    <button type="button" class="btn px-4 py-2 border border-gray-300" onclick="closeBackupConfigModal()">取消</button>
                    <button type="submit" class="btn btn-primary px-4 py-2">保存配置</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 备份进度模态框 -->
    <div id="backupProgressModal" class="modal">
        <div class="modal-content">
            <div class="text-center">
                <div class="mb-4">
                    <i class="fas fa-database text-4xl text-blue-500 animate-pulse"></i>
                </div>
                <h3 class="text-lg font-semibold mb-2">正在创建备份</h3>
                <p id="backupProgressText" class="text-gray-600 mb-4">备份中，请稍候...</p>
                <div class="w-full bg-gray-200 rounded-full h-2.5">
                    <div id="backupProgressBar" class="progress-bar bg-blue-500 h-2.5 rounded-full" style="width: 0%"></div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 恢复确认模态框 -->
    <div id="restoreConfirmModal" class="modal">
        <div class="modal-content">
            <div class="text-center mb-4">
                <i class="fas fa-exclamation-triangle text-4xl text-yellow-500 mb-4"></i>
                <h3 class="modal-title">确认恢复备份</h3>
                <p class="text-gray-600 mt-2">恢复备份将覆盖当前的密钥数据，确定继续吗？</p>
                <p class="text-sm text-red-600 mt-2">注意：此操作不可逆，请确保已做好当前数据的备份。</p>
            </div>
            
            <input type="hidden" id="restoreBackupId">
            
            <div class="mt-6 flex justify-end gap-3">
                <button class="btn px-4 py-2 border border-gray-300" onclick="closeRestoreConfirmModal()">取消</button>
                <button class="btn btn-primary px-4 py-2" onclick="confirmRestoreBackup()">确认恢复</button>
            </div>
        </div>
    </div>
    
    <!-- 密钥销毁确认模态框 -->
    <div id="destroyConfirmModal" class="modal">
        <div class="modal-content">
            <div class="text-center mb-4">
                <i class="fas fa-trash-alt text-4xl text-red-500 mb-4"></i>
                <h3 class="modal-title">确认销毁备用密钥</h3>
                <p class="text-gray-600 mt-2">销毁后将无法恢复，确定继续吗？</p>
            </div>
            
            <input type="hidden" id="destroyKeyId">
            
            <div class="mt-6 flex justify-end gap-3">
                <button class="btn px-4 py-2 border border-gray-300" onclick="closeDestroyConfirmModal()">取消</button>
                <button class="btn btn-danger px-4 py-2" onclick="confirmDestroyKey()">确认销毁</button>
            </div>
        </div>
    </div>
    
    <script>
        // 初始化数据
        function initData() {
            showLoading();
            
            // 初始化备份历史数据
            if (!localStorage.getItem('backupHistory')) {
                const initialBackupHistory = [
                    { 
                        id: 'BACK-001', 
                        time: '2024-01-15 16:30', 
                        keyCount: 15, 
                        size: '2.3 KB', 
                        type: '手动备份',
                        data: JSON.parse(localStorage.getItem('keys')) || []
                    },
                    { 
                        id: 'BACK-002', 
                        time: '2024-01-14 23:00', 
                        keyCount: 14, 
                        size: '2.1 KB', 
                        type: '自动备份',
                        data: JSON.parse(localStorage.getItem('keys')) || []
                    },
                    { 
                        id: 'BACK-003', 
                        time: '2024-01-13 23:00', 
                        keyCount: 14, 
                        size: '2.1 KB', 
                        type: '自动备份',
                        data: JSON.parse(localStorage.getItem('keys')) || []
                    },
                    { 
                        id: 'BACK-004', 
                        time: '2024-01-12 23:00', 
                        keyCount: 13, 
                        size: '2.0 KB', 
                        type: '自动备份',
                        data: JSON.parse(localStorage.getItem('keys')) || []
                    },
                    { 
                        id: 'BACK-005', 
                        time: '2024-01-11 23:00', 
                        keyCount: 13, 
                        size: '2.0 KB', 
                        type: '自动备份',
                        data: JSON.parse(localStorage.getItem('keys')) || []
                    }
                ];
                localStorage.setItem('backupHistory', JSON.stringify(initialBackupHistory));
            }
            
            // 初始化备用密钥数据
            if (!localStorage.getItem('spareKeys')) {
                const initialSpareKeys = [
                    { id: 'SPK-001', masterKeyId: 'KMS-001', masterKeyName: '主密钥A', generatedAt: '2024-01-10 15:30', status: 'active' },
                    { id: 'SPK-002', masterKeyId: 'KMS-002', masterKeyName: '数据加密密钥', generatedAt: '2024-01-12 09:15', status: 'active' },
                    { id: 'SPK-003', masterKeyId: 'KMS-004', masterKeyName: '备份密钥', generatedAt: '2024-01-14 14:45', status: 'active' }
                ];
                localStorage.setItem('spareKeys', JSON.stringify(initialSpareKeys));
            }
            
            hideLoading();
        }

        // 加载备份历史
        function loadBackupHistory() {
            showLoading();
            
            const backupHistory = JSON.parse(localStorage.getItem('backupHistory')) || [];
            const tbody = document.getElementById('backupHistoryTableBody');
            tbody.innerHTML = '';

            if (backupHistory.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="6" class="py-8">
                            <div class="empty-state">
                                <i class="fas fa-database"></i>
                                <p>暂无备份历史记录</p>
                                <p class="text-xs mt-1">点击"创建备份"创建您的第一个备份</p>
                            </div>
                        </td>
                    </tr>
                `;
            } else {
                backupHistory.forEach(backup => {
                    const row = document.createElement('tr');
                    row.className = 'table-row border-b border-gray-100';
                    row.innerHTML = `
                        <td class="py-3 px-4">${backup.id || '未知ID'}</td>
                        <td class="py-3 px-4">${backup.time || '未知时间'}</td>
                        <td class="py-3 px-4">${backup.keyCount || 0}</td>
                        <td class="py-3 px-4">${backup.size || '0 KB'}</td>
                        <td class="py-3 px-4">
                            <span class="status-badge ${(backup.type === '手动备份') ? 'manual' : 'auto'}">
                                ${backup.type || '自动备份'}
                            </span>
                        </td>
                        <td class="py-3 px-4">
                            <div class="flex gap-2">
                                <button onclick="downloadBackup('${backup.id}')" class="p-1 rounded hover:bg-blue-50 text-blue-600 hover:text-blue-800 transition-colors duration-300" title="下载备份">
                                    <i class="fas fa-download"></i>
                                </button>
                                <button onclick="showRestoreConfirm('${backup.id}')" class="p-1 rounded hover:bg-green-50 text-green-600 hover:text-green-800 transition-colors duration-300" title="恢复备份">
                                    <i class="fas fa-rotate-right"></i>
                                </button>
                                <button onclick="deleteBackup('${backup.id}')" class="p-1 rounded hover:bg-red-50 text-red-600 hover:text-red-800 transition-colors duration-300" title="删除备份">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </td>
                    `;
                    tbody.appendChild(row);
                });
            }
            
            hideLoading();
        }
        
        // 加载备用密钥列表
        function loadSpareKeys() {
            showLoading();
            
            try {
                const spareKeys = JSON.parse(localStorage.getItem('spareKeys') || '[]');
                const tbody = document.getElementById('spareKeysTableBody');
                tbody.innerHTML = '';
                
                if (spareKeys.length === 0) {
                    tbody.innerHTML = `
                        <tr>
                            <td colspan="5" class="py-8">
                                <div class="empty-state">
                                    <i class="fas fa-key"></i>
                                    <p>暂无备用密钥</p>
                                    <p class="text-xs mt-1">点击"生成备用密钥"创建备用密钥</p>
                                </div>
                            </td>
                        </tr>
                    `;
                } else {
                    spareKeys.forEach(key => {
                        const row = document.createElement('tr');
                        row.className = 'table-row border-b border-gray-100';
                        
                        row.innerHTML = `
                            <td class="py-3 px-4">${key.id || '未知ID'}</td>
                            <td class="py-3 px-4">${(key.masterKeyName || '未知主密钥')} (${key.masterKeyId || '未知ID'})</td>
                            <td class="py-3 px-4">${key.generatedAt || '未知时间'}</td>
                            <td class="py-3 px-4">
                                <span class="status-badge badge-success">活跃</span>
                            </td>
                            <td class="py-3 px-4">
                                <div class="flex gap-2">
                                    <button onclick="activateSpareKey('${key.id}')" class="p-1 rounded hover:bg-blue-50 text-blue-600 hover:text-blue-800 transition-colors duration-300" title="激活使用">
                                        <i class="fas fa-play-circle"></i>
                                    </button>
                                    <button onclick="showDestroyConfirm('${key.id}')" class="p-1 rounded hover:bg-red-50 text-red-600 hover:text-red-800 transition-colors duration-300" title="销毁">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        `;
                        tbody.appendChild(row);
                    });
                }
            } catch (error) {
                console.error('加载备用密钥失败:', error);
                showToast('加载数据失败', 'error');
            } finally {
                hideLoading();
            }
        }

        // 创建备份
        function createBackup() {
            const progressModal = document.getElementById('backupProgressModal');
            const progressBar = document.getElementById('backupProgressBar');
            const progressText = document.getElementById('backupProgressText');
            
            progressModal.classList.add('show');
            progressBar.style.width = '0%';
            progressText.textContent = '备份初始化中...';
            
            // 模拟备份进度
            let progress = 0;
            const interval = setInterval(function() {
                progress += Math.floor(Math.random() * 10) + 5;
                if (progress > 100) progress = 100;
                
                progressBar.style.width = progress + '%';
                
                if (progress < 30) {
                    progressText.textContent = '正在收集密钥数据...';
                } else if (progress < 60) {
                    progressText.textContent = '正在加密数据...';
                } else if (progress < 90) {
                    progressText.textContent = '正在生成备份文件...';
                } else {
                    progressText.textContent = '备份完成，正在保存...';
                }
                
                if (progress === 100) {
                    clearInterval(interval);
                    
                    // 模拟完成延迟
                    setTimeout(function() {
                        // 保存备份记录
                        try {
                            let keys = JSON.parse(localStorage.getItem('keys')) || [];
                            const backupHistory = JSON.parse(localStorage.getItem('backupHistory') || '[]');
                            const now = new Date();
                            const backupTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
                            
                            const newBackup = {
                                id: `BACK-${Date.now()}`,
                                time: backupTime,
                                keyCount: keys.length,
                                size: `${(JSON.stringify(keys).length / 1024).toFixed(1)} KB`,
                                type: '手动备份',
                                data: keys
                            };
                            
                            backupHistory.unshift(newBackup);
                            localStorage.setItem('backupHistory', JSON.stringify(backupHistory));
                            
                            // 下载备份文件
                            const blob = new Blob([JSON.stringify(keys, null, 2)], { type: 'application/json' });
                            const url = URL.createObjectURL(blob);
                            const a = document.createElement('a');
                            a.href = url;
                            a.download = `kms-backup-${new Date().toISOString().split('T')[0]}.json`;
                            document.body.appendChild(a);
                            a.click();
                            document.body.removeChild(a);
                            URL.revokeObjectURL(url);
                            
                            progressModal.classList.remove('show');
                            loadBackupHistory();
                            showToast('备份创建成功！', 'success');
                        } catch (error) {
                            console.error('创建备份失败:', error);
                            progressModal.classList.remove('show');
                            showToast('备份失败：' + error.message, 'error');
                        }
                    }, 1000);
                }
            }, 300);
        }

        // 恢复备份
        function restoreBackup() {
            const backupFile = document.getElementById('backupFile').files[0];
            const restorePassword = document.getElementById('restorePassword').value;

            if (!backupFile) {
                showToast('请选择备份文件！', 'error');
                return;
            }

            if (!restorePassword) {
                showToast('请输入备份密码！', 'error');
                return;
            }

            // 显示加载状态
            document.getElementById('restoreBtnText').textContent = '恢复中...';
            document.getElementById('restoreLoading').classList.remove('hidden');

            const reader = new FileReader();
            reader.onload = function(e) {
                try {
                    const backupData = JSON.parse(e.target.result);
                    
                    // 验证备份数据格式
                    if (!Array.isArray(backupData)) {
                        throw new Error('备份文件格式错误！');
                    }
                    
                    // 模拟密码验证
                    // 在实际系统中，这里会有真正的密码验证逻辑
                    
                    localStorage.setItem('keys', JSON.stringify(backupData));
                    
                    // 更新备份历史
                    const backupHistory = JSON.parse(localStorage.getItem('backupHistory')) || [];
                    const newBackup = {
                        id: `BACK-${Date.now()}`,
                        time: new Date().toLocaleString('zh-CN'),
                        keyCount: backupData.length,
                        size: `${(e.target.result.length / 1024).toFixed(1)} KB`,
                        type: '手动备份',
                        data: backupData
                    };
                    backupHistory.unshift(newBackup);
                    localStorage.setItem('backupHistory', JSON.stringify(backupHistory));
                    
                    loadBackupHistory();
                    
                    showToast('恢复成功！', 'success');
                    
                    // 重置表单
                    document.getElementById('backupFile').value = '';
                    document.getElementById('fileName').textContent = '';
                    document.getElementById('restorePassword').value = '';
                } catch (error) {
                    showToast('恢复失败：' + error.message, 'error');
                } finally {
                    // 隐藏加载状态
                    document.getElementById('restoreBtnText').textContent = '开始恢复';
                    document.getElementById('restoreLoading').classList.add('hidden');
                }
            };
            reader.readAsText(backupFile);
        }

        // 显示选择的文件名
        document.getElementById('backupFile').addEventListener('change', function(e) {
            const fileName = e.target.files[0]?.name || '';
            document.getElementById('fileName').textContent = fileName;
        });

        // 下载备份
        function downloadBackup(backupId) {
            const backupHistory = JSON.parse(localStorage.getItem('backupHistory')) || [];
            const backup = backupHistory.find(b => b.id === backupId);
            
            if (backup) {
                showLoading();
                
                // 模拟下载过程
                setTimeout(() => {
                    try {
                        const blob = new Blob([JSON.stringify(backup.data, null, 2)], { type: 'application/json' });
                        const url = URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = `kms-backup-${backup.id}-${backup.time.split(' ')[0]}.json`;
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                        URL.revokeObjectURL(url);
                        
                        showToast('备份文件下载成功！', 'success');
                    } catch (error) {
                        showToast('下载失败：' + error.message, 'error');
                    } finally {
                        hideLoading();
                    }
                }, 1000);
            }
        }

        // 生成备用密钥
        function generateSpareKeys() {
            showLoading();
            
            // 模拟生成延迟
            setTimeout(function() {
                try {
                    const keys = JSON.parse(localStorage.getItem('keys') || '[]');
                    const spareKeys = JSON.parse(localStorage.getItem('spareKeys') || '[]');
                    const activeKeys = keys.filter(function(key) {
                        return key.status === 'active';
                    });
                    
                    if (activeKeys.length === 0) {
                        hideLoading();
                        showToast('没有活跃的主密钥可生成备用密钥', 'warning');
                        return;
                    }
                    
                    // 为每个活跃主密钥生成备用密钥
                    activeKeys.forEach(function(key) {
                        const now = new Date();
                        const generatedAt = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
                        
                        const newSpareKey = {
                            id: `SPK-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
                            masterKeyId: key.id,
                            masterKeyName: key.name,
                            generatedAt: generatedAt,
                            status: 'active'
                        };
                        
                        spareKeys.push(newSpareKey);
                    });
                    
                    localStorage.setItem('spareKeys', JSON.stringify(spareKeys));
                    loadSpareKeys();
                    hideLoading();
                    showToast(`成功生成 ${activeKeys.length} 个备用密钥！`, 'success');
                } catch (error) {
                    console.error('生成备用密钥失败:', error);
                    hideLoading();
                    showToast('生成备用密钥失败', 'error');
                }
            }, 1500);
        }
        
        // 激活备用密钥
        function activateSpareKey(spareKeyId) {
            showLoading();
            
            // 模拟激活延迟
            setTimeout(function() {
                try {
                    const spareKeys = JSON.parse(localStorage.getItem('spareKeys') || '[]');
                    const spareKey = spareKeys.find(function(key) {
                        return key.id === spareKeyId;
                    });
                    
                    if (spareKey) {
                        // 这里应该有更多的业务逻辑，比如更新主密钥
                        hideLoading();
                        showToast(`备用密钥 ${spareKey.id} 已成功激活，替换了主密钥 ${spareKey.masterKeyName}`, 'success');
                    } else {
                        hideLoading();
                        showToast('备用密钥不存在', 'error');
                    }
                } catch (error) {
                    console.error('激活备用密钥失败:', error);
                    hideLoading();
                    showToast('激活备用密钥失败', 'error');
                }
            }, 1000);
        }
        
        // 显示恢复确认
        function showRestoreConfirm(backupId) {
            document.getElementById('restoreBackupId').value = backupId;
            document.getElementById('restoreConfirmModal').classList.add('show');
        }
        
        // 确认恢复备份
        function confirmRestoreBackup() {
            const backupId = document.getElementById('restoreBackupId').value;
            showLoading();
            
            // 模拟恢复延迟
            setTimeout(function() {
                try {
                    const backupHistory = JSON.parse(localStorage.getItem('backupHistory') || '[]');
                    const backup = backupHistory.find(function(b) {
                        return b.id === backupId;
                    });
                    
                    if (backup) {
                        localStorage.setItem('keys', JSON.stringify(backup.data));
                        closeRestoreConfirmModal();
                        hideLoading();
                        showToast(`备份 ${backup.id} 恢复成功！`, 'success');
                    } else {
                        closeRestoreConfirmModal();
                        hideLoading();
                        showToast('备份不存在', 'error');
                    }
                } catch (error) {
                    console.error('恢复备份失败:', error);
                    closeRestoreConfirmModal();
                    hideLoading();
                    showToast('恢复备份失败', 'error');
                }
            }, 2000);
        }
        
        // 显示销毁确认
        function showDestroyConfirm(keyId) {
            document.getElementById('destroyKeyId').value = keyId;
            document.getElementById('destroyConfirmModal').classList.add('show');
        }
        
        // 确认销毁密钥
        function confirmDestroyKey() {
            const keyId = document.getElementById('destroyKeyId').value;
            
            try {
                let spareKeys = JSON.parse(localStorage.getItem('spareKeys') || '[]');
                spareKeys = spareKeys.filter(function(key) {
                    return key.id !== keyId;
                });
                localStorage.setItem('spareKeys', JSON.stringify(spareKeys));
                closeDestroyConfirmModal();
                loadSpareKeys();
                showToast('备用密钥已销毁！', 'success');
            } catch (error) {
                console.error('销毁备用密钥失败:', error);
                closeDestroyConfirmModal();
                showToast('销毁备用密钥失败', 'error');
            }
        }
        
        // 打开备份配置模态框
        function openBackupConfigModal() {
            document.getElementById('backupConfigModal').classList.add('show');
        }
        
        // 提交备份配置
        function submitBackupConfig(event) {
            event.preventDefault();
            
            const mode = document.getElementById('configBackupMode').value;
            const cycle = document.getElementById('configBackupCycle').value;
            const retention = document.getElementById('configBackupRetention').value;
            const encryption = document.getElementById('configBackupEncryption').value;
            
            try {
                // 保存配置
                const backupConfig = {
                    mode: mode,
                    cycle: cycle,
                    retention: retention,
                    encryption: encryption
                };
                localStorage.setItem('backupConfig', JSON.stringify(backupConfig));
                
                // 更新显示
                document.getElementById('backupMode').textContent = mode === 'manual' ? '手动备份' : '定时备份';
                document.getElementById('backupCycle').textContent = 
                    cycle === 'daily' ? '每日 23:00' : 
                    cycle === 'weekly' ? '每周日 23:00' : '每月1日 23:00';
                document.getElementById('backupRetention').textContent = `${retention} 天`;
                
                closeBackupConfigModal();
                showToast('备份配置保存成功！', 'success');
            } catch (error) {
                console.error('保存备份配置失败:', error);
                showToast('保存配置失败', 'error');
            }
        }
        
        // 关闭模态框函数
        function closeBackupConfigModal() { document.getElementById('backupConfigModal').classList.remove('show'); }
        function closeRestoreConfirmModal() { document.getElementById('restoreConfirmModal').classList.remove('show'); }
        function closeDestroyConfirmModal() { document.getElementById('destroyConfirmModal').classList.remove('show'); }
        function closeBackupProgressModal() { document.getElementById('backupProgressModal').classList.remove('show'); }
        
        // 设置搜索功能
        function setupSearch() {
            const searchInput = document.getElementById('backupSearch');
            
            searchInput.addEventListener('input', function() {
                const searchTerm = searchInput.value.toLowerCase();
                const backupHistory = JSON.parse(localStorage.getItem('backupHistory') || '[]');
                const filteredBackups = backupHistory.filter(function(backup) {
                    return backup.id.toLowerCase().includes(searchTerm) || 
                           backup.type.toLowerCase().includes(searchTerm);
                });
                
                // 重新渲染表格
                const tbody = document.getElementById('backupHistoryTableBody');
                tbody.innerHTML = '';
                
                if (filteredBackups.length === 0) {
                    tbody.innerHTML = `
                        <tr>
                            <td colspan="6" class="py-8">
                                <div class="empty-state">
                                    <i class="fas fa-search"></i>
                                    <p>没有找到匹配的备份</p>
                                </div>
                            </td>
                        </tr>
                    `;
                } else {
                    filteredBackups.forEach(function(backup) {
                        const row = document.createElement('tr');
                        row.className = 'table-row border-b border-gray-100';
                        
                        row.innerHTML = `
                            <td class="py-3 px-4">${backup.id}</td>
                            <td class="py-3 px-4">${backup.time}</td>
                            <td class="py-3 px-4">${backup.keyCount}</td>
                            <td class="py-3 px-4">${backup.size}</td>
                            <td class="py-3 px-4">
                                <span class="status-badge ${backup.type === '手动备份' ? 'manual' : 'auto'}">
                                    ${backup.type}
                                </span>
                            </td>
                            <td class="py-3 px-4">
                                <div class="flex gap-2">
                                    <button onclick="downloadBackup('${backup.id}')" class="p-1 rounded hover:bg-blue-50 text-blue-600 hover:text-blue-800 transition-colors duration-300" title="下载备份">
                                        <i class="fas fa-download"></i>
                                    </button>
                                    <button onclick="showRestoreConfirm('${backup.id}')" class="p-1 rounded hover:bg-green-50 text-green-600 hover:text-green-800 transition-colors duration-300" title="恢复备份">
                                        <i class="fas fa-rotate-right"></i>
                                    </button>
                                    <button onclick="deleteBackup('${backup.id}')" class="p-1 rounded hover:bg-red-50 text-red-600 hover:text-red-800 transition-colors duration-300" title="删除备份">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        `;
                        tbody.appendChild(row);
                    });
                }
            });
        }

        // 删除备份
        function deleteBackup(backupId) {
            if (confirm('确定要删除此备份吗？删除后将无法恢复！')) {
                showLoading();
                
                // 模拟删除过程
                setTimeout(() => {
                    try {
                        const backupHistory = JSON.parse(localStorage.getItem('backupHistory')) || [];
                        const updatedBackupHistory = backupHistory.filter(backup => backup.id !== backupId);
                        localStorage.setItem('backupHistory', JSON.stringify(updatedBackupHistory));
                        loadBackupHistory();
                        showToast('备份已成功删除！', 'success');
                    } catch (error) {
                        showToast('删除失败：' + error.message, 'error');
                    } finally {
                        hideLoading();
                    }
                }, 800);
            }
        }

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 延迟加载以展示动画效果
            setTimeout(function() {
                initData();
                loadBackupHistory();
                loadSpareKeys();
                setupSearch();
                
                // 加载备份配置
                try {
                    const config = JSON.parse(localStorage.getItem('backupConfig') || '{}');
                    if (config.mode) {
                        document.getElementById('backupMode').textContent = config.mode === 'manual' ? '手动备份' : '定时备份';
                        document.getElementById('backupCycle').textContent = 
                            config.cycle === 'daily' ? '每日 23:00' : 
                            config.cycle === 'weekly' ? '每周日 23:00' : '每月1日 23:00';
                        document.getElementById('backupRetention').textContent = `${config.retention || 30} 天`;
                    }
                } catch (error) {
                    console.error('加载备份配置失败:', error);
                }
            }, 100);
        });
        
        // 点击模态框外部关闭
        document.addEventListener('click', function(e) {
            const modals = ['backupConfigModal', 'restoreConfirmModal', 'destroyConfirmModal', 'backupProgressModal'];
            modals.forEach(function(modalId) {
                const modal = document.getElementById(modalId);
                if (e.target === modal && modal.classList.contains('show')) {
                    modal.classList.remove('show');
                }
            });
        });
        
        // ESC键关闭模态框
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                const modals = ['backupConfigModal', 'restoreConfirmModal', 'destroyConfirmModal', 'backupProgressModal'];
                modals.forEach(function(modalId) {
                    document.getElementById(modalId).classList.remove('show');
                });
            }
        });
        
        // 密码强度检测
        function checkPasswordStrength(password) {
            if (password.length === 0) {
                return { message: '', className: 'text-gray-500' };
            } else if (password.length < 6) {
                return { message: '密码强度：弱', className: 'text-red-500' };
            } else if (password.length < 10) {
                return { message: '密码强度：中', className: 'text-yellow-500' };
            } else {
                return { message: '密码强度：强', className: 'text-green-500' };
            }
        }
    </script>
</body>
</html>